package com.blb.community.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.blb.community.utils.JwtUtil;
import com.blb.community.utils.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 帅帅
 * @Date 2022/6/27 18:53
 * @PackageName:com.blb._20220625springboot_jwt.config
 * @ClassName: TokenAuthenticationFiiter
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    private static final String HEADER = "Authorization";

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //在请求头里获取
        String token = request.getHeader(HEADER);

        if (StringUtils.isEmpty(token)) {
            //请求头里不存在则在参数里获取
            token = request.getParameter(HEADER);
        }

        // 如果参数为空放行验证失败
        if (StringUtils.isEmpty(token)) {
            chain.doFilter(request, response);
            return;
        }
        //解析token
        String usernameFromToken = JwtUtil.getUsernameFromToken(token, RsaUtil.publicKey);
        if (usernameFromToken !=  null) {
            try {

                User user = new User(usernameFromToken, "", AuthorityUtils.commaSeparatedStringToAuthorityList(""));
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, "", AuthorityUtils.commaSeparatedStringToAuthorityList(""));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("解析错误");
            }
            chain.doFilter(request, response);
        }
    }
}
